package com.hs.srm.admin.modules.harmfulsubstance.controller;

import cn.hutool.core.util.ObjectUtil;
import com.hs.srm.admin.modules.harmfulsubstance.entity.SvhcHeadEntity;
import com.hs.srm.admin.modules.harmfulsubstance.entity.SvhcItemEntity;
import com.hs.srm.admin.modules.harmfulsubstance.entity.SvhcVendorHeadEntity;
import com.hs.srm.admin.modules.harmfulsubstance.entity.SvhcVendorItemEntity;
import com.hs.srm.admin.modules.harmfulsubstance.service.SvhcHeadService;
import com.hs.srm.admin.modules.harmfulsubstance.service.SvhcItemService;
import com.hs.srm.admin.modules.harmfulsubstance.service.SvhcVendorHeadService;
import com.hs.srm.admin.modules.harmfulsubstance.service.SvhcVendorItemService;
import com.hs.srm.admin.modules.harmfulsubstance.vo.SvhcVendorVO;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;

/**
 * 高度关注物质Controller
 *
 * @author ych
 * @since 2020-03-12 09:11:25
 */
@RestController
@RequestMapping("/svhc")
public class SvhcController extends AbstractController {

    @Resource
    private SvhcItemService svhcItemService;

    @Resource
    private SvhcHeadService svhcHeadService;

    @Resource
    private VendorService vendorService;

    @Autowired
    private SvhcVendorHeadService vendorHeadService;

    @Autowired
    private SvhcVendorItemService vendorItemService;

    /**
     * 高度关注物质新增页面
     *
     * @return
     */
    @GetMapping("/addSVhc")
    public ModelAndView addSVhc() {
        ModelAndView modelAndView = new ModelAndView("modules/harmful/substance_add");
        return modelAndView;
    }

    /**
     * 查询列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = svhcItemService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 保存添加的物质
     *
     * @param list
     * @return
     */
    @SysLog("关注物质添加")
    @PostMapping("/save")
    @Transactional(rollbackFor=Exception.class)
    public R save(@RequestBody List<SvhcItemEntity> list) {
        SvhcHeadEntity svhcHeadEntity = new SvhcHeadEntity();
        //创建日期
        svhcHeadEntity.setCreateDate(new Date());
        //创建人
        svhcHeadEntity.setCreator(this.getUser().getUsername());
        //保存头信息
        svhcHeadService.insert(svhcHeadEntity);
        list.forEach(itemEntity -> {
            //创建日期
            itemEntity.setCreateDate(new Date());
            //head id
            itemEntity.setHeadId(svhcHeadEntity.getPkId());
            //添加人姓名
            itemEntity.setCreator(this.getUser().getName());
        });
        //保存新增的行项目信息
        svhcItemService.insertBatch(list);
        return R.ok();
    }

    /**
     * 删除关注物质
     *
     * @param itemIds
     * @return
     */
    @SysLog("删除关注物质")
    @RequestMapping("/deleteSvhc")
    public R deleteOrders(@RequestParam(value = "itemIds") String[] itemIds) {
        List<SvhcItemEntity> svhcItemEntities = svhcItemService.selectBatchIds(Arrays.asList(itemIds));
        svhcItemEntities.forEach(item -> {
            item.setDeleteFlag(SvhcItemEntity.SHANCHU);
            item.setDeleteDate(new Date());
            //删除人账号
            item.setDeletePerson(this.getUser().getUsername());
        });
        boolean b = svhcItemService.updateBatchById(svhcItemEntities);
        if (!b) {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 供应商填写关注物质查询列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/subVendorList")
    public R subVendorList(@RequestParam Map<String, Object> params) {
        PageUtils page;
        //供应商登录，则username为供应商编码
        String userName = this.getUser().getUsername();
        VendorInfoEntity vendorInfoEntity = vendorService.selectByVendorCode(userName);
        //当前用户为供应商
        if (ObjectUtil.isNotNull(vendorInfoEntity)) {
            //将sapCode放入map，查询条件
            params.put("sapCode", userName);
            page = svhcHeadService.queryPage(params);
        } else {//当前用户为SQE
            page = vendorHeadService.queryPage(params);
        }
        return R.ok(page);
    }

    /**
     * 查询供应商填写的关注物质详情
     *
     * @param svhcVendorHeadId
     * @return
     */
    @RequestMapping("/findById/{pkId}")
    public R findById(@PathVariable("pkId") String svhcVendorHeadId) {
        List<SvhcVendorVO> vendorVOS = vendorItemService.selectSvhc(svhcVendorHeadId);
        return R.ok(vendorVOS);
    }

    /**
     * 供应商填写SQE新增的关注物质清单
     *
     * @param svhcHeadId svhc_head表id，以此字段从item表中获取详细列表
     * @return
     */
    @RequiresPermissions("substanceVendor:edit")
    @GetMapping("/edit/{svhcHeadId}")
    public ModelAndView edit(@PathVariable("svhcHeadId") String svhcHeadId) {
        Map<String, Object> map = new HashMap<>();
        map.put("head_id", svhcHeadId);
        List<SvhcItemEntity> svhcItemEntities = svhcItemService.selectByMap(map);
        ModelAndView modelAndView = new ModelAndView("modules/harmful/substance_vendor_edit");
        modelAndView.addObject("svhcItemEntities", svhcItemEntities);
        return modelAndView;
    }

    /**
     * 供应商填写关注物质清单，保存数据
     *
     * @param list
     * @return
     */
    @SysLog("供应商填写关注物质清单")
    @RequiresPermissions("substanceVendor:edit")
    @PostMapping("/saveVendorEdit")
    public R saveVendorEdit(@RequestBody List<SvhcVendorVO> list) {
        //SvhcVendorHead表中SvhcHead表id，此字段用于将供应商填写的清单与SQE哪一次新增的清单关联
        SvhcVendorHeadEntity vendorHeadEntity = new SvhcVendorHeadEntity(list.get(0).getSvhcHeadId(), this.getUser().getUsername(), new Date());
        vendorHeadService.insert(vendorHeadEntity);

        //将表头数据插入数据库，然后获取表头id放入item中
        List<SvhcVendorItemEntity> itemList = new ArrayList<>();
        list.forEach(vo -> {
            itemList.add(new SvhcVendorItemEntity(vo.getSvhcHeadId(), vo.getSvhcItemId(), vendorHeadEntity.getPkId(), vo.getContain(), vo.getPpm(), vo.getDescription()));
        });
        vendorItemService.insertBatch(itemList);
        return R.ok();
    }
}